package pandabay.DAO;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;

import pandabay.service.NewUser;

public class UserDAO {
	private NewUser newUser;

	public void saveUser(NewUser newUser) throws Exception {
		//write to XML document
		this.newUser = newUser;	
		System.out.println("success so far");
		
				XStream xstream = new XStream(new StaxDriver());
				String xml = xstream.toXML(newUser);
				FileWriter writer;
				String target = newUser.getEmail() + ".xml";
					try {
						writer = new FileWriter("db/" + target);
						BufferedWriter out = new BufferedWriter(writer);
						out.write(xml);
						out.close();
						writer.close();
						
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	}
	
	public NewUser readUser(String target) {
		// read from XML file
		NewUser newUser = null;
		try {
			// retrieve saved newUser Object (if possible)			
			File savedUserConfig = new File("db/" + target + ".xml");
			FileReader fileReader = new FileReader(savedUserConfig);
			BufferedReader reader = new BufferedReader(fileReader);
			StringBuilder stringBuilder = new StringBuilder();
			String line = "";
			while((line = reader.readLine()) != null) {
				stringBuilder.append(line);
			}
			XStream xstream = new XStream(new StaxDriver());
			newUser = (NewUser)xstream.fromXML(stringBuilder.toString());
//			System.out.println(newUser.getForename());
		} catch(Exception ex) {
			ex.printStackTrace();
		}
		return newUser;

	}

}
